package com.ruoyi.sywx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sywx.domain.*;
import com.ruoyi.sywx.domain.bo.*;
import com.ruoyi.sywx.domain.vo.SywxYqVo;
import com.ruoyi.sywx.domain.vo.YqPosterLinkVo;
import com.ruoyi.sywx.domain.vo.YqUnitLinkVo;
import com.ruoyi.sywx.mapper.SywxYqMapper;
import com.ruoyi.sywx.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 舆情Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-09
 */
@RequiredArgsConstructor
@Service
public class SywxYqServiceImpl implements ISywxYqService {

    private final SywxYqMapper baseMapper;
    private final ISywxYqAnnexService iSywxYqAnnexService;
    private final ISywxYqFeedbackService iSywxYqFeedbackService;
    private final IYqUnitLinkService iYqUnitLinkService;
    private final IYqPosterLinkService iYqPosterLinkService;

    /**
     * 查询舆情
     */
    @Override
    public SywxYqVo queryById(Long id){
        SywxYqVo vo = baseMapper.selectVoById(id);
        // 设置舆情和发帖人关联表
        YqPosterLinkBo yqPosterLinkBo = new YqPosterLinkBo();
        yqPosterLinkBo.setYqId(id);
        List<YqPosterLinkVo> yqPosterLinkVos = iYqPosterLinkService.queryList(yqPosterLinkBo);
        if (CollectionUtils.isNotEmpty(yqPosterLinkVos)) {
            List<Long> posterIds = yqPosterLinkVos.stream().map(e -> e.getPosterId()).collect(Collectors.toList());
            vo.setYqPoster(posterIds);
        }
        // 设置舆情和涉情单位关联表
        YqUnitLinkBo bo = new YqUnitLinkBo();
        bo.setYqId(id);
        List<YqUnitLinkVo> yqUnitLinkVos = iYqUnitLinkService.queryList(bo);
        if (CollectionUtils.isNotEmpty(yqUnitLinkVos)) {
            List<Long> unitList = yqUnitLinkVos.stream().map(e -> e.getUnitId()).collect(Collectors.toList());
            vo.setYqUnit(unitList);
        }
        // 设置反馈和附件
        List<SywxYqAnnex> annexs = iSywxYqAnnexService.queryByYqId(id);
        if (CollectionUtils.isNotEmpty(annexs)) {
            String annexIds = annexs.stream().map(e -> String.valueOf(e.getOssId())).collect(Collectors.joining(","));
            vo.setAnnex(annexIds);
        }
        List<SywxYqFeedback> feedbacks = iSywxYqFeedbackService.queryByYqId(id);
        if (CollectionUtils.isNotEmpty(feedbacks)) {
            String feedbackIds = feedbacks.stream().map(e -> String.valueOf(e.getOssId())).collect(Collectors.joining(","));
            vo.setFeedback(feedbackIds);
        }
        return vo;
    }

    /**
     * 查询舆情列表
     */
    @Override
    public TableDataInfo<SywxYqVo> queryPageList(SywxYqBo bo, PageQuery pageQuery) {
        Page<SywxYqVo> result = baseMapper.selectPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询舆情列表
     */
    @Override
    public List<SywxYqVo> queryList(SywxYqBo bo) {
        LambdaQueryWrapper<SywxYq> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SywxYq> buildQueryWrapper(SywxYqBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SywxYq> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPosterId() != null, SywxYq::getPosterId, bo.getPosterId());
        lqw.eq(bo.getOccurDate() != null, SywxYq::getOccurDate, bo.getOccurDate());
        lqw.eq(StringUtils.isNotBlank(bo.getLevel()), SywxYq::getLevel, bo.getLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SywxYq::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), SywxYq::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增舆情
     */
    @Override
    @Transactional
    public Boolean insertByBo(SywxYqBo bo) {
        SywxYq add = BeanUtil.toBean(bo, SywxYq.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        // 新增发帖人表
        if (CollectionUtils.isNotEmpty(bo.getYqPoster())) {
            List<YqPosterLink> yqPosterLinkList = new ArrayList<>();
            bo.getYqPoster().forEach(e->{
                YqPosterLink yqPoster = new YqPosterLink();
                yqPoster.setYqId(add.getId());
                yqPoster.setPosterId(e);
                yqPosterLinkList.add(yqPoster);
            });
            boolean flagPosterLink = iYqPosterLinkService.insertBatch(yqPosterLinkList);
        }
        // 新增涉情单位和舆情关联表
        List<YqUnitLink> yqUnitLinkList = new ArrayList<>();
        bo.getYqUnit().forEach(e->{
            YqUnitLink yqUnitLink = new YqUnitLink();
            yqUnitLink.setUnitId(e);
            yqUnitLink.setYqId(add.getId());
            yqUnitLinkList.add(yqUnitLink);
        });
        boolean flagUnitLink = iYqUnitLinkService.insertBatch(yqUnitLinkList);
        if (StringUtils.isNotBlank(bo.getAnnex())) {
            List<Long> annexList = Arrays.asList(bo.getAnnex().split(","))
                .stream().map(item -> Long.parseLong(item)).collect(Collectors.toList());
            // 保存附件表
            List<SywxYqAnnexBo> annexeBos = new ArrayList<>();
            annexList.forEach(e -> {
                SywxYqAnnexBo annexBo = new SywxYqAnnexBo();
                annexBo.setYqId(add.getId());
                annexBo.setOssId(e);
                annexeBos.add(annexBo);
            });
            iSywxYqAnnexService.insertBatchByBoList(annexeBos);
        }
        if (StringUtils.isNotBlank(bo.getFeedback())) {
            List<Long> feedback = Arrays.asList(bo.getFeedback().split(","))
                .stream().map(item -> Long.parseLong(item)).collect(Collectors.toList());
            // 保存反馈表
            List<SywxYqFeedbackBo> feedbackBos = new ArrayList<>();
            feedback.forEach(e -> {
                SywxYqFeedbackBo feedbackBo = new SywxYqFeedbackBo();
                feedbackBo.setYqId(add.getId());
                feedbackBo.setOssId(e);
                feedbackBos.add(feedbackBo);
            });
            iSywxYqFeedbackService.insertBatchByBoList(feedbackBos);
        }
        return flag;
    }

    /**
     * 修改舆情
     */
    @Override
    @Transactional
    public Boolean updateByBo(SywxYqBo bo) {
        SywxYq update = BeanUtil.toBean(bo, SywxYq.class);
        validEntityBeforeSave(update);
        // 删除舆情和发帖人关联表
        boolean deletePosterLink = iYqPosterLinkService.deleteByYqId(update.getId());
        if (CollectionUtils.isNotEmpty(bo.getYqPoster())) {
            List<YqPosterLink> yqPosterLinkList = new ArrayList<>();
            bo.getYqPoster().forEach(e->{
                YqPosterLink yqPoster = new YqPosterLink();
                yqPoster.setYqId(update.getId());
                yqPoster.setPosterId(e);
                yqPosterLinkList.add(yqPoster);
            });
            boolean flagPosterLink = iYqPosterLinkService.insertBatch(yqPosterLinkList);
        }
        // 删除并新增涉情单位和舆情关联表
        List<YqUnitLink> yqUnitLinkList = new ArrayList<>();
        bo.getYqUnit().forEach(e->{
            YqUnitLink yqUnitLink = new YqUnitLink();
            yqUnitLink.setUnitId(e);
            yqUnitLink.setYqId(update.getId());
            yqUnitLinkList.add(yqUnitLink);
        });
        boolean deleteUnitLink = iYqUnitLinkService.deleteByYqId(update.getId());
        boolean flagUnitLink = iYqUnitLinkService.insertBatch(yqUnitLinkList);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SywxYq entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除舆情
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<SywxYqVo> sjfx(SywxYqBo bo) {
        if (StringUtils.isEmpty(bo.getSjfxType())) {
            throw new RuntimeException("分析类型不能为空");
        }
        List<SywxYqVo> sjfxyqfl = new ArrayList<>();
        // 根据舆情分类分析
        if (bo.getSjfxType().equals("1")) {
            sjfxyqfl = baseMapper.sjfxyqfl(bo);
        }
        // 根据涉情单位分析
        if (bo.getSjfxType().equals("2")) {
            sjfxyqfl = baseMapper.sjfxsqdw(bo);
        }
        return sjfxyqfl;
    }
}
